package com.jsgt.greekfire.ui.mainassets

import android.app.Activity
import android.content.Intent
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.fhx.core.base.BaseActivity
import com.fhx.core.utils.LogUtils
import com.fhx.core.utils.NetworkUtil
import com.fhx.core.utils.ToastUtils
import com.jsgt.greekfire.R
import com.jsgt.greekfire.bean.ConvertConfigBean
import com.jsgt.greekfire.dialog.SecurityPwdDialog
import com.jsgt.greekfire.event.TransferEvent
import com.jsgt.greekfire.factory.CoinViewModelFactory
import com.jsgt.greekfire.viewmodel.CoinViewModel
import kotlinx.android.synthetic.main.activity_convert.*
import kotlinx.android.synthetic.main.view_title.*
import org.greenrobot.eventbus.EventBus

class ConvertActivity : BaseActivity(), View.OnClickListener {
    private val coinViewModel: CoinViewModel by lazy {
        ViewModelProvider(
            this,
            CoinViewModelFactory()
        ).get(CoinViewModel::class.java)
    }
    private var currency: String? = null
    private var convertCurrency: String? = null
    private var accountNum: String? = null
    private val REQUEST_CURRENCY = 1000
    private val REQUEST_FROM_ACCOUNT = 1001
    private var currentSymbol: String? = null
    private var toAssetId: String? = null
    private var toAccount: String? = null
    private var fromAssetId: String? = null
    private var fromAccount: String? = null
    private var pwdDialog: SecurityPwdDialog? = null
    var convertConfigList: List<ConvertConfigBean>? = null

    override fun getLayoutId(): Int = R.layout.activity_convert
    override fun main() {
        var symbol = intent.getStringExtra("symbol")
        fromAssetId = intent.getStringExtra("assetGuid")
        if (!TextUtils.isEmpty(symbol)) {
            tvCurrency.setText(symbol)
            fromAccount = symbol
        }
        title_tv?.text = resources.getString(R.string.transfer_btn)
        btnConvert.setOnClickListener {
            currency = tvCurrency.text.toString()
            convertCurrency = tvConvertCurrency.text.toString()
            accountNum = etAccountNum.text.trim().toString()
            if (verifyInfo(currency!!, convertCurrency!!, accountNum!!)) {
                if (NetworkUtil.isNetworkAvailable()) {
                    val num = etAccountNum.text.toString().trim()
                    initDialog()
                    pwdDialog?.numberTv?.text = num
                    pwdDialog?.show()
                } else {
                    ToastUtils.showNetUnAvailableToast()
                }
            }
        }
        tvCurrency.setOnClickListener(this)
        tvConvertCurrency.setOnClickListener(this)
        ivExchange.setOnClickListener(this)
        coinViewModel.convertConfigData.observe(this, Observer {
            convertConfigList = it.result
        })
        coinViewModel.convertCoinData.observe(this, Observer {
            showProgress(false)
            ToastUtils.show(this, resources.getString(R.string.exchange_success))
            EventBus.getDefault().post(TransferEvent(etAccountNum.text.toString()))
            pwdDialog?.dismiss()
            finish()
        })
        coinViewModel.errorLiveData.observe(this, Observer {
            showProgress(false)
            pwdDialog?.dismiss()
            showToast(it.toString())
        })
        etAccountNum.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {

            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                setExchangeNum(s.toString().trim())
            }
        })
    }

    private fun setExchangeNum(s: String?) {
        var text = resources.getString(R.string.exchange_num)
        val currency = tvCurrency.text.toString().trim()
        val convertCurrency = tvConvertCurrency.text.toString().trim()
        if (!TextUtils.isEmpty(s.toString().trim()) && !TextUtils.isEmpty(currency) && !TextUtils.isEmpty(convertCurrency)) {
            if (!TextUtils.isEmpty(currency) && !TextUtils.isEmpty(convertCurrency) && convertConfigList != null && convertConfigList!!.size > 0) {
                for (index in convertConfigList!!) {
                    if (currency.equals(index.coin)) {
                        for (toAssetListBean in index!!.toAssetList!!) {
                            if (convertCurrency.equals(toAssetListBean.coin)) {
                                var num = s.toString().trim().toDouble()
                                var price = num * index.price / toAssetListBean.price
                                tvConvertNum.setText(text + " " + price + toAssetListBean.coin)
                            }
                        }
                    }
                }
            }
        } else {
            tvConvertNum.setText(text + "0.00")
        }
    }

    private fun initDialog() {
        pwdDialog = SecurityPwdDialog(this, R.style.dialog)
        pwdDialog?.inputCallback = object : SecurityPwdDialog.InputCallback {
            override fun callBack(result: String) {
                val num = etAccountNum.text.toString().trim()
                showProgress(true)
                coinViewModel.convertCoin(
                    fromAssetId!!,
                    toAssetId!!,
                    fromAccount!!,
                    toAccount!!,
                    num,
                    result
                )
            }
        }
    }


    private fun verifyInfo(
        currency: String,
        currentSymbol: String,
        etAccountNum: String
    ): Boolean {
        if (TextUtils.isEmpty(currency)) {
            showToast(resources.getString(R.string.convert_hint_currency1))
            return false
        } else if (TextUtils.isEmpty(currentSymbol)) {
            showToast(resources.getString(R.string.convert_hint_currency1))
            return false
        } else if (TextUtils.isEmpty(etAccountNum)) {
            showToast(resources.getString(R.string.convert_hint_num))
            return false
        }
        return true
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.tvCurrency -> {
                var intent = Intent(this, ConvertConfigListActivity::class.java)
                intent.putExtra("symbol", tvConvertCurrency.text.toString().trim())
                startActivityForResult(intent, REQUEST_FROM_ACCOUNT)
            }
            R.id.tvConvertCurrency -> {
                var intent = Intent(this, ConvertConfigListActivity::class.java)
                intent.putExtra("symbol", tvCurrency.text.toString().trim())
                startActivityForResult(intent, REQUEST_CURRENCY)
            }
            R.id.ivExchange -> {
                if (!TextUtils.isEmpty(toAccount)) {
                    setAccountText()
                    var num = etAccountNum.text.toString().trim()
                    setExchangeNum(num)
                }
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CURRENCY && resultCode == Activity.RESULT_OK) {
            currentSymbol = data!!.getStringExtra("currentSymbol")
            toAssetId = data.getStringExtra("assetGuid")
            if (!TextUtils.isEmpty(currentSymbol)) {
                tvConvertCurrency.setText(currentSymbol)
                toAccount = currentSymbol
            }
        } else if (requestCode == REQUEST_FROM_ACCOUNT && resultCode == Activity.RESULT_OK) {
            currentSymbol = data!!.getStringExtra("currentSymbol")
            fromAssetId = data.getStringExtra("assetGuid")
            tvCurrency.setText(currentSymbol)
            fromAccount = currentSymbol
        }
        var num = etAccountNum.text.toString().trim()
        setExchangeNum(num);
    }

    /**c
     * 更新账户文字
     */
    private fun setAccountText() {
        tvCurrency.setHintTextColor(resources.getColor(R.color.color_999999))
        if (!TextUtils.isEmpty(fromAssetId) && !TextUtils.isEmpty(toAssetId) && convertConfigList != null && convertConfigList!!.size > 0) {
            for (index in convertConfigList!!) {
                if (toAssetId!!.equals(index.fromAssetId.toString())) {
                    if (index.toAssetIds.toString()!!.contains(fromAssetId!!)) {
                        var temp: String? = null
                        var tempAssetId: String? = null
                        temp = fromAccount
                        fromAccount = toAccount
                        toAccount = temp
                        //交换id
                        tempAssetId = fromAssetId
                        fromAssetId = toAssetId
                        toAssetId = tempAssetId
                        tvCurrency.text = fromAccount
                        tvConvertCurrency.text = toAccount
                        break
                    } else {
                        var temp: String? = null
                        var tempAssetId: String? = null
                        temp = fromAccount
                        fromAccount = toAccount
                        toAccount = temp
                        //交换id
                        tempAssetId = fromAssetId
                        fromAssetId = toAssetId
                        toAssetId = tempAssetId
                        tvCurrency.text = fromAccount
                        tvConvertCurrency.text = ""
                        toAssetId = ""
                        toAccount = ""
                        break
                    }
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        pwdDialog = null
    }

    override fun onResume() {
        super.onResume()
        coinViewModel.convertConfigList()
    }
}